<?php
namespace app\common\library\traits;
use think\Request;
use think\Db;
use think\Response;
use think\exception\HttpResponseException;
use think\Config;
use think\View as ViewTemplate;
trait Backend
{	
	/**
	* 析构函数
	*/
	public function __destruct()
	{
		if(Request()->isPost() === true){
			// 后置方法
	        if ($this->afterActionList && $this->error === false) {
	            foreach ($this->afterActionList as $method => $options) {
	                is_numeric($method) ?
	                $this->afterAction($options) :
	                $this->afterAction($method, $options);
	            }
	        }
		}
	}
	/**
     * 后置操作
     * @access protected
     * @param  string $method  前置操作方法名
     * @param  array  $options 调用参数 ['only'=>[...]] 或者 ['except'=>[...]]
     * @return void
     */
    protected function afterAction($method, $options = [])
    {
        if (isset($options['only'])) {
            if (is_string($options['only'])) {
                $options['only'] = explode(',', $options['only']);
            }

            if (!in_array($this->request->action(), $options['only'])) {
                return;
            }
        } elseif (isset($options['except'])) {
            if (is_string($options['except'])) {
                $options['except'] = explode(',', $options['except']);
            }

            if (in_array($this->request->action(), $options['except'])) {
                return;
            }
        }
        call_user_func([$this, $method]);
    }
	 /**
	 * 操作错误跳转的快捷方法
	 * @access protected
	 * @param mixed  $msg    提示信息
	 * @param string $url    跳转的 URL 地址
	 * @param mixed  $data   返回的数据
	 * @param int    $wait   跳转等待时间
	 * @param array  $header 发送的 Header 信息
	 * @return void
	 * @throws HttpResponseException
	 */
    protected function error($msg = '', $url = null, $data = '', $wait = 3, array $header = [])
    {
        if (is_null($url)) {
            $url = Request::instance()->isAjax() ? '' : 'javascript:history.back(-1);';
        } elseif ('' !== $url && !strpos($url, '://') && 0 !== strpos($url, '/')) {
            $url = Url::build($url);
        }

        $type = $this->getResponseType();
        $result = [
            'code' => 0,
            'msg'  => $msg,
            'data' => $data,
            'url'  => $url,
            'wait' => $wait,
        ];

        if ('html' == strtolower($type)) {
            $template = Config::get('template');
            $view = Config::get('view_replace_str');

            $result = ViewTemplate::instance($template, $view)
                ->fetch(Config::get('dispatch_error_tmpl'), $result);
        }
        $response = Response::create($result, $type)->header($header);
        $this->error = true;
        throw new HttpResponseException($response);
    }
	/**
	 * 关键字检索
	 * @param array $search 检索字段
	 */
	protected function keyword_search($search)
	{
		if( $search == '' || empty($this->keyword_search) ) return '';
		$where = '';
		foreach($this->keyword_search as $key => $val){
			if($len = strpos($val,'.')){//判断是否取别名
				$val = '`'.substr($val,0,$len).'`.`'.substr($val,$len+1).'`';
			}else{
				$val = '`'.$val.'`';
			}
			if($where == ''){
				$where .= $val . " like '%{$search}%'";
			}else{
				$where .= " or ". $val . " like '%{$search}%'";
			}
		}
		return $where;
	}
	/**
	 * 获取列表数据
	 * @param array $data 提交的参数
	 */
	protected function getList($data)
	{
		$page = isset($data['page']) ? $data['page'] : 1;
		$row = isset($data['limit']) ? $data['limit'] : $this->row;
		$search_arr = isset($data['keyword']) ? $data['keyword'] : '';
		$search = $this->keyword_search($search_arr);
		// print_r($search);
		$order = $this->order;
		$where = $this->handleList($data);
		
		$list = $this->model->listData($where, $order, $page, $row, $search);
		// echo $this->model->getlastsql();
		$list = collection($list)->toArray();
		$count = $this->model->listCount($where, $order, $search);
		return $this->jsonList(0, config('status.SUCCESS_ONE'), $count, $list, $page, $row);
	}
	/**
	 * 列表数据处理
	 * @param array $data 数据参数
	 */
	protected function handleList($data)
	{
		return [];
	}
	/**
	 * layui表格，返回数据
	 * @param  intger $code  状态码
	 * @param  string $msg   错误信息
	 * @param  intger $count 总条数
	 * @param  array $data  数据集合
	 * @param  intger $page 当前页
	 * @param  intger $row  每页条数
	 * @return json
	 */
	protected function jsonList($code, $msg, $count, $data, $page, $row)
	{
		return json(['code'=>$code,'msg'=>$msg,'count'=>$count,'data'=>$data,'page'=>$page,'row'=>$row]);
	}
	/**
     * 下载csv文件
     * @param array $head csv列名信息
     * @param array $data 数据
     * @param string $name 导出csv文件名字
     * @param array $field 字段及顺序
     */
    protected function export_csv( $head , $data , $name , $field )
    {
        $file_name = $name . time() . ".csv";
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename='.$file_name );
        header('Cache-Control: max-age=0');
        // 打开PHP文件句柄，php://output 表示直接输出到浏览器
        $file = fopen('php://output',"a");
        //列名信息
        foreach ($head as $i => $v) {
            // CSV的Excel支持GBK编码，一定要转换，否则乱码
            $head[$i] = iconv('utf-8', 'gbk', $v);
        }
        // 将数据通过fputcsv写到文件句柄
        fputcsv($file, $head);
        //数据信息
        if($data){
        	foreach( $data as $k => $v ){
	            foreach( $v as $ke => $ve ){
	                $v[$ke] = iconv('utf-8', 'gbk', $ve);
	            }
	            $arr = [];
	            foreach( $field as $fi ){
	                $arr[] = $v[$fi];
	            }
	            fputcsv($file,$arr);
	        }
        }
        fclose($file);
        exit();
    }
	/**
	 * 本月时间区间
	 * @return array 开始时间+结束时间
	 */
	protected function activeTime()
	{
		return [
			mktime(0, 0, 0, date('m'), 1, date('Y')),
			mktime(23, 59, 59, date('m'), date('t'), date('Y'))
		];
	}
	/**
	 * 上个月时间区间
	 * @return array 开始时间+结束时间
	 */
	protected function preTime()
	{
		$m = mktime(0, 0, 0, date('m')-1, 1, date('Y'));
		$t = date('t',$m);
		return [
			$m,
			mktime(23, 59, 59, date('m')-1, $t, date('Y'))
		];
	}
	/**
	 * 自定义时间区间
	 * @param  array $data 自定义时间参数
	 */
	protected function cusTime($data)
	{
		/*@时间*/
		if(isset($data['start']) && $data['start'] != '' && isset($data['end']) && $data['end'] != ''){
			if(strtotime($data['start']) > strtotime($data['end'])){
				return false;
			}
			return ['between',[strtotime($data['start']),strtotime($data['end'])]];
		}else if(isset($data['start']) && $data['start'] != ''){
			return ['>=',strtotime($data['start'])];
		}else if(isset($data['end']) && $data['end'] != ''){
			return ['<=',strtotime($data['end'])];
		}
	}
	/**
	* 维修提成计算
	*/
	protected function repairRatio($people_money, $ratio)
	{
		return floor( intval(strval($people_money*100)) * intval(strval($ratio)) /100)/100;
	}
} 
